package com.esd.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esd.common.pojo.PageResult;
import com.esd.common.pojo.R;
import com.esd.common.utils.MD5Utils;
import com.esd.shiro.BaseService;
import com.esd.sys.dao.UserMapper;
import com.esd.sys.entity.User;
import com.esd.sys.entity.dto.PwdDto;
import com.esd.sys.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * 服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, BaseService {

    @Override
    public R userLogin(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String newPwd = MD5Utils.md5Encryption(password, username); //明文密码加密
        User UserInfo = getOne(
                new LambdaQueryWrapper<User>().eq(
                        User::getUsername,
                        username
                ).eq(User::getPassword, newPwd));

        if (ObjectUtils.isEmpty(UserInfo)) {
            return R.error("用户名或密码不正确！");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUsername(),
                newPwd
        );
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            return R.error("用户名不存在！");
        } catch (AuthenticationException e) {
            return R.error("账号或密码错误！");
        } catch (AuthorizationException e) {
            return R.error("没有权限");
        }
        return R.ok("登录成功！！");
    }

    @Override
    public R getUserAll(Map<String , Object> params) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        if (params.get("username") != null && !params.get("username").toString().trim().equals("")) {
            queryWrapper.like(User::getUsername, params.get("username").toString().trim());
        }

        if (params.get("cname") != null && !params.get("cname").toString().trim().equals("")) {
            queryWrapper.like(User::getCname, params.get("cname").toString().trim());
        }

        if (params.get("phone") != null && !params.get("phone").toString().trim().equals("")) {
            queryWrapper.like(User::getPhone, params.get("phone").toString().trim());
        }

        Page<User> userPage = this.page(
                new Page<>(
                        (Integer)params.get("currentPage"),
                        (Integer)params.get("pageSize")
                ),
                queryWrapper);
        return R.ok(new PageResult(userPage.getTotal(),userPage.getRecords()));
    }

    @Override
    public R addUser(User user) {
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getUsername, user.getUsername());
        User selectOne = baseMapper.selectOne(query);
        if (selectOne != null) {
            return R.error("该用户名已存在！");
        }
        user.setPassword(MD5Utils.md5Encryption(user.getPassword(), user.getUsername()));
        int i = baseMapper.insert(user);
        return i > 0 ? R.ok("添加用户成功！！"):R.error("添加用户失败！！");
    }

    @Override
    public R updateUser(User user) {
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getUsername, user.getUsername());
        User selectOne = baseMapper.selectOne(query);
        if (selectOne != null && !Objects.equals(selectOne.getUserId(), user.getUserId())) {
            return R.error("该用户名已存在！");
        }
        user.setPassword(MD5Utils.md5Encryption(user.getPassword(), user.getUsername()));
        return baseMapper.updateById(user) > 0 ? R.ok("用户信息修改成功！！") : R.error("用户信息修改失败！！") ;
    }

    @Override
    public R updateUserPwd(PwdDto pwdDto) {
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getUsername, pwdDto.getUsername())
                .eq(User::getPassword , MD5Utils.md5Encryption(pwdDto.getOldPwd(),pwdDto.getUsername()));
        User selectOne = baseMapper.selectOne(query);
        if (selectOne == null) {
            return R.error("原密码输入错误 ！！");
        }else {
            Subject currentUser = SecurityUtils.getSubject();
            // 退出登录
            currentUser.logout();
            selectOne.setPassword(MD5Utils.md5Encryption(pwdDto.getNewPwd(), pwdDto.getUsername()));
            int i = baseMapper.updateById(selectOne);
            return i > 0? R.ok("修改密码成功！！") : R.error("修改密码失败！！");
        }
    }

    @Override
    public R deleteUserById(Long userId) {
        long count = this.count();
        if (count <= 1) {
            return R.error("最后一个用户不能删除！！");
        }
        baseMapper.deleteById(userId);
        return R.ok("删除用户成功！！");
    }


    @Override
    public User getByUsername(String username) {
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getUsername, username);
        return baseMapper.selectOne(query);
    }


}
